package gofile

import (
	"bufio"
	"errors"
	"gitee.com/zhouhailin/gopkg/gostrings"
	"io"
	"os"
)

// ReadText 从文件中读取文本内容
func ReadText(pathname string) (string, error) {
	data, err := os.ReadFile(pathname)
	if err != nil {
		return "", err
	}
	return string(data), nil
}

// WriteText 向文件中写入文本内容，会覆盖旧内容
func WriteText(pathname string, text string) error {
	err := os.WriteFile(pathname, []byte(text), 0770)
	if err != nil {
		return err
	}
	return nil
}

// AppendText 向文件中追加文本内容
func AppendText(pathname string, text string) error {
	file, err := os.OpenFile(pathname, os.O_CREATE|os.O_APPEND, 0770)
	if err != nil {
		return err
	}
	defer func() { _ = file.Close() }()
	writer := bufio.NewWriter(file)
	_, err = writer.WriteString(text)
	if err != nil {
		return err
	}
	err0 := writer.Flush()
	if err0 != nil {
		return err0
	}
	return nil
}

// ReadLines 从文件中读取文本内容行
func ReadLines(pathname string) ([]string, error) {
	var lines []string
	file, err := os.OpenFile(pathname, os.O_RDONLY, 0770)
	if err != nil {
		return lines, err
	}
	defer func() { _ = file.Close() }()
	reader := bufio.NewReader(file)
	for {
		line, err := reader.ReadString('\n')
		if err != nil || io.EOF == err {
			break
		}
		lines = append(lines, line)
	}
	return lines, nil
}

// WriteLines 向文件中写入文本内容行
func WriteLines(pathname string, lines []string) error {
	text := ""
	for _, line := range lines {
		text += line + gostrings.LF
	}
	return WriteText(pathname, text)
}

// AppendLines 向文件中追加文本内容行
func AppendLines(pathname string, lines []string) error {
	text := ""
	for _, line := range lines {
		text += line + "\n"
	}
	return AppendText(pathname, text)
}

// DeleteFile 删除文件
func DeleteFile(pathname string) error {
	fileInfo, err := os.Stat(pathname)
	if err != nil {
		return err
	}
	if fileInfo.IsDir() {
		return errors.New(pathname + " is directory.")
	}
	err = os.Remove(pathname)
	if err != nil {
		return err
	}
	return nil
}

// IsFile 判断是否为文件
func IsFile(pathname string) bool {
	fileInfo, err := os.Stat(pathname)
	if err != nil {
		return false
	}
	if fileInfo.IsDir() {
		return false
	}
	return true
}
